import { Injectable } from "@nestjs/common";
import { CreateRoleDto } from "./dto/create-role.dto";
import { UpdateRoleDto } from "./dto/update-role.dto";
import { ObjectId } from "mongodb";
import { Core } from "src/core";

@Injectable()
export class RoleService {
    create(createRoleDto: CreateRoleDto) {
        return this.getCollection().insertOne({
            ...createRoleDto,
            createdAt: new Date(),
            updatedAt: new Date()
        });
    }

    async findAll() {
        const ary = await this.getCollection().find({}).toArray();
        return ary;
    }

    async findOne(id: string) {
        const ary = await this.getCollection().findOne({ _id: new ObjectId(id) });
        return ary;
    }

    async findMany(ids: string[]) {
        const objectIds = ids.map(id => new ObjectId(id));
        const documents = await this.getCollection().find({ _id: { $in: objectIds } }).toArray();
        return documents;
    }

    async update(id: string, updateRoleDto: UpdateRoleDto) {
        const filter = { _id: new ObjectId(id) };
        const update = { $set: { ...updateRoleDto, updatedAt: new Date() } };
        const result = await this.getCollection().updateOne(filter, update);

        // //设置
        // db.users.update({ _id: 1 }, { $set: { roles: [] } });
        // //添加
        // db.users.update({ _id: 1 }, { $addToSet: { roles: 1 } });
        // 批量查找
        // db.users.find({ "_id": { "$in": [1, 2, 3, 4, 6, 7] } })

        return `Updated ${result.modifiedCount} document(s)`;
    }

    async remove(id: string) {
        const insertResult = await this.getCollection().deleteOne({ _id: new ObjectId(id) });
        return insertResult.deletedCount.toString();
    }
    getCollection() {
        return Core.ins.db.collection("role");
    }
}
